using System;

using Gtk;

namespace repragator
{
	public class MovementButtonArgs
	{
		public double Distance
		{
			get;
			set;
		}
		
		public string Axis
		{
			get;
			set;
		}
		
		public int Feedrate
		{
			get;
			set;
		}
		
		public MovementButtonArgs(string axis, int feedrate)
		{
			this.Distance = -999;
			
			this.Axis = axis;
			
			this.Feedrate = feedrate;
		}
		
		public MovementButtonArgs(double distance, string axis, int feedrate)
			: this(axis, feedrate)
		{
			this.Distance = distance;
		}
	}
	
	public delegate void MovementButtonClickedHandler(object sender, MovementButtonArgs e);
	
	[System.ComponentModel.ToolboxItem(true)]
	public partial class MovementButtonBox : Gtk.Bin
	{
		public string[] Buttons
		{
			get;
			set;
		}
		
		public string Axis
		{
			get;
			set;
		}
		
		public int Feedrate
		{
			get
			{
				return (int)this.feedrateSpinButton.Value;
			}
			set
			{
				this.feedrateSpinButton.Value = value;		
			}
		}
	
		private bool loaded = false;
		
		public event MovementButtonClickedHandler MovementButtonClickedEvent;
		
		public MovementButtonBox ()
		{
			this.Build ();
		}

		protected void OnExposeEvent (object o, Gtk.ExposeEventArgs args)
		{
			if (!this.loaded)
			{
				Button b;
				
				foreach (string button in this.Buttons)
				{
					if (button == "b")
					{
						Label l = new Label();
						
						l.WidthRequest = 50;
						
						this.buttonBox.PackStart(l, false, false, 0);
					}
					else
					{
						b = new Button();
						
						b.Clicked += new EventHandler(this.ButtonClicked);
						
						b.WidthRequest = 50;
						
						b.Label = button;
						
						this.buttonBox.PackStart(b, false, false, 0);
					}
				}
				
				switch (this.Axis.ToLower())
				{
				case "x":
				case "y":
					this.feedrateSpinButton.Adjustment.Upper = 5000;
					this.feedrateSpinButton.Adjustment.Lower = 1;
					this.feedrateSpinButton.Value = 2000;
					break;
				case "z":
					this.feedrateSpinButton.Adjustment.Upper = 1000;
					this.feedrateSpinButton.Adjustment.Lower = 1;
					this.feedrateSpinButton.Value = 200;
					break;
				}
				
				this.ShowAll();
				
				this.loaded = true;
			}
			
			args.RetVal = true;
		}
		
		protected void ButtonClicked(object sender, EventArgs e)
		{
			Button b = (Button)sender;
			
			if (this.MovementButtonClickedEvent != null)
			{
				if (b.Label == "Home")
				{
					this.MovementButtonClickedEvent(this, new MovementButtonArgs(this.Axis, (int)this.feedrateSpinButton.Value));
				}
				else
				{
					this.MovementButtonClickedEvent(this, new MovementButtonArgs(double.Parse(b.Label), this.Axis, (int)this.feedrateSpinButton.Value));
				}
			}
		}
	}
}

